package com.enation.app.shop.front.api.webController;

import com.enation.app.base.core.service.IMemberManager;
import com.enation.app.shop.core.goods.model.Product;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IProductManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.service.IOrderManager;
import com.enation.app.shop.core.order.service.OrderStatus;
import com.enation.app.shop.front.api.utils.IdCardUtil;
import com.enation.app.shop.front.api.inpolicy.entity.InPolicy;
import com.enation.app.shop.front.api.inpolicy.service.IInpolicyManager;
import com.enation.framework.action.JsonResult;
import com.enation.framework.database.IDaoSupport;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.JsonResultUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Random;
@Scope("prototype")
@Controller
@RequestMapping("/app/warranty")
public class WarrantyWebController {
    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private IInpolicyManager iInpolicyManager;
    @Autowired
    private IDaoSupport daoSupport;
    @Autowired
    private IProductManager productManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private IMemberManager memberManager;
    @Autowired
    private IGoodsManager goodsManager;

    //PC创建保单
    @ResponseBody
    @RequestMapping("/web/addWarranty")
    public JsonResult addWarranty(HttpServletRequest request) {
        String ds = request.getParameter("policyInfo");
        JSONObject jsonObject = JSONObject.fromObject(ds);
        System.out.println(jsonObject.toString());
        InPolicy warranty1 = new InPolicy();
        int a = 0;
        warranty1.setGoods_id(Integer.parseInt(jsonObject.get("goods_id").toString()));
        warranty1.setWarranty_number(createSn());
        warranty1.setUser_id(Integer.parseInt(jsonObject.get("user_id").toString()));
        warranty1.setApplicant_name(jsonObject.get("applicant_name").toString());
        warranty1.setInsurant_name(jsonObject.get("insurant_name").toString());
        String monthNumber = jsonObject.get("effective_month").toString();
        int monthNumber1 = Integer.parseInt(monthNumber);
        warranty1.setMonthnumber(monthNumber1);
        warranty1.setEffective_month(monthNumber);
        int insured_qunatiy = Integer.parseInt(jsonObject.get("insured_quantity").toString());
        warranty1.setInsured_quantity(insured_qunatiy);
        Product product = productManager.getByGoodsId(Integer.parseInt(jsonObject.get("goods_id").toString()));
        double insured_price = product.getPrice();
        warranty1.setInsured_price(insured_price);
        String created_at = jsonObject.get("created_at").toString() ;
        warranty1.setCreated_at(new Timestamp(System.currentTimeMillis()));
        warranty1.setPolicy_address(jsonObject.get("policy_address").toString());
        //验证身份证号
        if (!IdCardUtil.validate(jsonObject.get("policy_idcard").toString().trim())) {
            return JsonResultUtil.getErrorJson("请输入正确的身份证号码！");
        }else{
            warranty1.setPolicy_idcard(jsonObject.get("policy_idcard").toString());
        }
        //验证手机号
        if (jsonObject.get("policy_mobile").toString().length() != 11) {
            return JsonResultUtil.getErrorJson("请输入正确的手机号！");
        }else{
             warranty1.setPolicy_mobile(jsonObject.get("policy_mobile").toString());
        }
        BigDecimal bigDecimal1 = new BigDecimal(jsonObject.get("max_premium_amount").toString());
        BigDecimal bigDecimal2 = new BigDecimal(jsonObject.get("premium_amount").toString());
        BigDecimal bigDecimal3 = new BigDecimal(jsonObject.getDouble("max_premium_amount"));
        warranty1.setMax_premium_amount(bigDecimal3);
        Double countPrice = bigDecimal2.multiply(bigDecimal1).doubleValue();
        BigDecimal bigDecimal4 = new BigDecimal(countPrice);
        warranty1.setPremium_amount(bigDecimal4);
        a = iInpolicyManager.createWarranty(warranty1);
        if (a != 1) {
            return JsonResultUtil.getErrorJson("创建保单失败!");
        } else {
            return JsonResultUtil.getSuccessJson("创建保单成功!",warranty1.getWarranty_number());
        }
    }

    //查看报单详情
    @ResponseBody
    @RequestMapping("/web/getWarrantyById")
    public ModelAndView getWarrantyById(HttpServletRequest request, Integer paymoney){
        String warrantyNumber = request.getParameter("warrantynumber");
        ModelAndView model = new ModelAndView("/themes/kaben/createWarrantyOrder");
        InPolicy warranty = iInpolicyManager.warranty(warrantyNumber);
        model.addObject(warranty);
        model.addObject("paymoney",paymoney);
        return model;
    }


    private String createSn() {
        boolean isHave = true;  //数据库中是否存在该保单
        String sn = "";            //保单号

        //如果存在当前保单
        while (isHave) {
            StringBuffer snSb = new StringBuffer(DateUtil.getDateline() + "");
            snSb.append(new Random().nextInt(100 - 10) + 10);
            String sql = "SELECT count(*) FROM rbt_inpolicy WHERE warranty_number = '" + snSb.toString() + "'";
            int count = this.daoSupport.queryForInt(sql);
            if (count == 0) {
                sn = snSb.toString();
                isHave = false;
            }
        }
        return sn;
    }
    //创建订单
    @ResponseBody
    @RequestMapping("/createWarrantyOrder")
    public JsonResult addOrder(HttpServletRequest request){
        String ds = request.getParameter("policy");
        JSONObject jsonObject = JSONObject.fromObject(ds);
        Order order = new Order();
        order.setSn(jsonObject.get("warranty_number").toString());
        int memberid = Integer.parseInt(jsonObject.get("member_id").toString());
        order.setMember_id(memberid);
        //支付信息
        order.setPayment_id(5);
        order.setStatus(OrderStatus.ORDER_COMPLETE);
        order.setPayment_name("信用额度支付");
        order.setPayment_type("online");
        order.setPayment_account(jsonObject.get("payment_acount").toString());
        order.setPaymoney(Double.parseDouble(jsonObject.get("paymoney").toString()));
        String create_time = jsonObject.get("create_time").toString();
        order.setCreate_time(DateUtil.stringToLong(create_time,""));
        //收货人联系方式
        order.setShip_name(jsonObject.get("ship_name").toString());
        order.setShip_addr(jsonObject.get("ship_addr").toString());
        String ship_mobile = jsonObject.get("ship_mobile").toString();
        if(ship_mobile.length()!=11){
            return JsonResultUtil.getErrorJson("请输入正确的手机号码!");
        }else{
            order.setShip_mobile(ship_mobile);
        }
        order.setShip_tel(jsonObject.get("ship_tel").toString());
        order.setShip_zip(jsonObject.get("ship_zip").toString());

        String protect_price = jsonObject.get("protect_price").toString();
        order.setProtect_price(Double.parseDouble(protect_price));
        String goods_amount = jsonObject.get("goods_amount").toString();//商品总额
        order.setGoods_amount(Double.parseDouble(goods_amount));
        String order_amount = jsonObject.get("order_amount").toString();//订单总额
        order.setOrder_amount(Double.parseDouble(order_amount));
        String goods_num = jsonObject.get("goods_num").toString();
        order.setGoods_num(Integer.parseInt(goods_num));
        String gainedpoint = jsonObject.get("gainedpoint").toString();//积分
        order.setGainedpoint(Integer.parseInt(gainedpoint));
        order.setRemark(jsonObject.get("remark").toString());
        order.setDiscount(0.00);
        //发票
        int recepit = Integer.parseInt(jsonObject.get("receipt").toString());//是否需要发票 1需要,2不需要
        if(recepit==1){
            order.setReceipt(recepit);
            Integer recepit_type = Integer.valueOf(jsonObject.get("recepit_type").toString());
            order.setReceipt_type(recepit_type);
            order.setReceipt_title(jsonObject.get("recepit_title").toString());
            order.setReceipt_name(jsonObject.get("recepit_name").toString());
        }
        orderManager.add(order);
        this.logger.error(order);
        return JsonResultUtil.getObjectMessageJson(order,"成功创建订单!");
    }













}
